import {
	wxLoginApi,
	getUserInfoApi,
	wxlogoutApi // 引入退出登录接口
} from "@/api/auth.js"

export default {
	namespaced: true,
	state: {
		tokenValue: "",
		tokenName: "",
		id: "",
		username: "",
		avatar: "",
	},
	actions: {
		// 微信登录
		wxLogin({
			commit
		}, code) {
			return new Promise(async (resolve, reject) => {
				try {
					const resp = await wxLoginApi(code)
					commit('SET_TOKEN', resp.data.tokenValue)
					commit('SET_TOKEN_NAME', resp.data.tokenName)
					uni.setStorageSync('token', resp.data)

					const userInfo = await getUserInfoApi()
					uni.setStorageSync('userInfo', userInfo.data)
					commit('SET_ID', userInfo.data.id)
					commit('SET_USERNAME', userInfo.data.username)
					commit('SET_AVATAR', userInfo.data.avatar)

					resolve()
				} catch (e) {
					console.log(e);
					reject(e.message)
				}
			})
		},

		// 退出登录
		async logout({
			commit
		}) {
			try {
				// 调用退出登录接口
				await wxlogoutApi()
			} catch (e) {
				console.log('退出登录接口调用失败', e)
			} finally {
				// 清除本地存储和Vuex状态
				uni.removeStorageSync('token')
				uni.removeStorageSync('userInfo')
				uni.removeStorageSync('isLogin')
				commit('SET_TOKEN', '')
				commit('SET_TOKEN_NAME', '')
				commit('SET_ID', '')
				commit('SET_USERNAME', '')
				commit('SET_AVATAR', '')
			}
		},

		// 从缓存加载数据
		getCache({
			commit
		}) {
			try {
				if (uni.getStorageSync('token')) {
					const token = uni.getStorageSync('token')
					commit('SET_TOKEN', token.tokenValue)
					commit('SET_TOKEN_NAME', token.tokenName)
				}
				if (uni.getStorageSync('userInfo')) {
					const userInfo = uni.getStorageSync('userInfo')
					commit('SET_ID', userInfo.id)
					commit('SET_USERNAME', userInfo.username)
					commit('SET_AVATAR', userInfo.avatar)
				}
			} catch (e) {
				console.log(e);
			}
		},
	},
	mutations: {
		// 设置Token名称
		SET_TOKEN_NAME(store, tokenName) {
			store.tokenName = tokenName
		},
		// 设置Token值
		SET_TOKEN(store, tokenValue) {
			store.tokenValue = tokenValue
		},
		// 统一设置Token（新增，解决之前的报错）
		setToken(store, {
			tokenName,
			tokenValue
		}) {
			store.tokenName = tokenName
			store.tokenValue = tokenValue
		},
		// 设置用户ID
		SET_ID(store, id) {
			store.id = id
		},
		// 设置用户名
		SET_USERNAME(store, username) {
			store.username = username
		},
		// 设置头像
		SET_AVATAR(store, avatar) {
			store.avatar = avatar
		}
	},
	getters: {
		// 可添加需要的计算属性
		isLogin(state) {
			return !!state.tokenValue
		}
	}
}